<template>
  <div class="work-order-list">
    <CommonHeader title="采购入库单-批次列表" :isShowBack="true" :tem="false">
      <template>
        <span>
          <img
            src="@/assets/images/common/back.png"
            class="back-img"
            @click="goBack"
          />
        </span>
      </template>
    </CommonHeader>
    <section class="search-box">
      <div class="inner">
        <van-search
          v-model="searchParams.compositeSearch"
          readonly
          placeholder="搜索"
          @search="onSearch"
          @cancel="onCancel"
          @click="showSearch"
          @click-right-icon.stop="clear"
          >
            <template #right-icon>
              <van-icon name="cross" />
            </template>
          </van-search>
      </div>
      <SearchForm
       ref="SearchForm"
        :search-flag="searchFlag"
        :search-form="searchParams"
        @cancel="handleCancelSearch"
        @confirm="handleConfirmSearch"
      />
    </section>
    <CommonMain>
      <template>
        <van-pull-refresh
          v-model="refreshing"
          :disabled="isRefreshDisable"
          @refresh="onRefresh"
        >
          <van-list
            v-if="list.length > 0"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <listItem :list="list" @selectMaterial="selectMaterial"> </listItem>
          </van-list>
          <div v-if="!loading && this.list.length == 0" class="no-data">
            暂无数据
          </div>
        </van-pull-refresh>
        <Toasts v-show="toastShow" />
      </template>
    </CommonMain>
    <div class="model-footer-wrap footer">
      <!-- <div class="footer-l"> -->
      <!-- <van-checkbox v-model="allChecked" shape="square" @click="checkedChange"
          >全选</van-checkbox
        > -->
      <!-- </div> -->

      <van-button
        type="primary"
        block
        round
        color="#548af1"
        size="normal"
        :loading="btnLoading"
        loading-text="正在提交..."
        @click="selectSubmit"
        >确定</van-button
      >
    </div>
    <img
      src="@/assets/images/allocation/scan.png"
      class="scan-img"
      v-draggable
      @click="scanChange"
    />
  </div>
</template>
  
  <script>
import listItem from "./components/item.vue";
import CommonHeader from "@/components/CommonHeader/index.vue";
import CommonMain from "@/components/CommonMain/index.vue";
import SearchForm from "./components/SearchForm.vue";
import { getList, productionSelect } from "@/api/allocation";
import { inventoryList, pdaAdd } from "@/api/inventory";
import Vue from "vue";
import Toasts from "@/components/Toast";
import { Dialog, Toast } from "vant";

// 全局注册
Vue.use(Dialog);
Vue.use(Toast);

// -------------------------------------------------------------------
import { handleScanData } from "@/utils/common";

export default {
  components: {
    SearchForm,
    CommonHeader,
    CommonMain,
    listItem,
    Toasts,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      allChecked: false,
      btnLoading: false,
      loading: false,
      list: [],
      searchParams: {
        states: "2",
        current: 1,
        size: 10,
      },
      refreshing: false,
      finished: false, // 列表
      toastShow: false,
      // ---------------------------------------
      total: 0,
      //   搜索组件
      searchFlag: false,
      search: "",
      //   扫码提示弹框
      isShowConfirmDialog: false,
      // 滚动与下拉冲突
      scrollTop: 0,
      isRefreshDisable: false,
      isRequest: false,
      // 完成弹窗
      show: false,
      selectMaterialData: {},
    };
  },
  watch: {
    scrollTop(newval) {
      if (newval > 0) {
        this.isRefreshDisable = true;
      } else {
        this.isRefreshDisable = false;
      }
    },
  },
  created() {},
  mounted() {
    this.getList();
    const that = this;
    // PDA扫码
    window["QrcodeMsg"] = (res) => {
      if (res) {
        console.log(res, "ScanCodeMsg这是首页");
        that.searchParams.compositeSearch = res;
        that.onRefresh();
      }
    };
    // 扫码枪扫码
    window["ScanCodeMsg"] = (res) => {
      if (res) {
        console.log(res, "ScanCodeMsg这是首页");
        that.searchParams.compositeSearch = res;
        that.onRefresh();
      }
    };
  },
  methods: {
    clear(){
      this.$refs.SearchForm.cancel()
    },
    goBack() {
      if(this.$route.query.type == 'allocationDetailForm'){
        this.$router.push({
          path: "/allocationDetail/form",
          query: {
            id: this.$route.query.id,
            orderNumber: this.$route.query.orderNumber,
            warehouseCode: this.$route.query.warehouseCode,
            materialInfo: this.$route.query.materialInfo,
          },
        });
      }else{
        this.$router.push({
          path: "/batch",
          query: {
            id: this.$route.query.id,
            orderNumber: this.$route.query.orderNumber,
            warehouseCode: this.$route.query.warehouseCode,
            materialInfo: this.$route.query.materialInfo,
          },
        })
      }
      
    },
    // 手动拉起相机
    scanChange() {
      // this.handleScanData('salechuku-20221125ffff')
      // this.handleScanData('salechuku-20221125ffff')
      const that = this;
      if (process.env.NODE_ENV === "development") {
        that.searchParams.compositeSearch = "testwangzai";
        that.onRefresh();
      } else {
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
          if (res) {
            console.log(res, "qrCode");
            that.searchParams.compositeSearch = res;
            that.onRefresh();
          }
        });
      }
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      this.list = [];
      this.searchParams.current = 1;
      this.getList();
    },
    async getList() {
      this.loading = true;
      this.refreshing = true;
      const result = await inventoryList({
        ...this.searchParams,
        locationQuantityGtZero: 1,
        warehouseCode: this.$route.query.warehouseCode,
        skuId:this.$route.query.skuId || 0,
        materialCode:JSON.parse(this.$route.query.materialInfo).code,
        materialCodeEqual:1
      });
      this.refreshing = false;
      this.loading = false;
      const { code, data = {} } = result.data || {};
      if (code == "200") {
        data.records.map((i) => {
          i.materialQualityName = i.materialQuality == 1 ? "合格" : "不合格";
          i.isBatchMag = i.isBatchMag ? 1 : 0;
          i.checked = false;
          const selectData = JSON.parse(localStorage.getItem('selectData')) || {}
          if(i.inventoryDetailId == selectData.stockMaterialDetaiList?.inventoryDetailId){
            i.checked = true;
          }
        });

        if (this.searchParams.current > 1) {
          this.list = this.list.concat(data.records);
        } else {
          this.list = data.records;
        }

        this.total = data.total;
        if (
          this.total <= this.list.length ||
          data.records.length == 0 ||
          data.records.length < this.searchParams.size
        ) {
          this.finished = true;
        }
      } else {
        Toast.fail("系统繁忙");
      }
    },
    // 确认搜索
    handleConfirmSearch(val) {
      // this.searchParams = val
      let detaultParams = {
        current: this.searchParams.current,
        size: this.searchParams.size,
        statusList: this.searchParams.statusList,
      };
      this.searchParams = { ...detaultParams, ...val };
      this.searchFlag = false;
      this.onRefresh();
    },
    // 重置搜索
    handleCancelSearch(val) {
      let detaultParams = {
        current: this.searchParams.current,
        size: this.searchParams.size,
        statusList: this.searchParams.statusList,
      };
      this.searchParams = { ...detaultParams, ...val };
      this.searchFlag = false;
      this.onRefresh();
    },
    // 弹出搜索框
    showSearch() {
      this.searchFlag = !this.searchFlag;
    },
    // 搜索
    onSearch() {
      console.log(this.search);
    },
    // 取消搜索
    onCancel() {
      this.searchFlag = false;
    },
    // 加载更多
    onLoad() {
      if (this.finished) {
        return;
      }
      console.log("滚到了底部");
      this.searchParams.current += 1;
      this.getList();
    },
    async handleScanData(val) {
      if (this.isRequest) {
        return;
      }
      this.isRequest = true;
      setTimeout(() => {
        this.isRequest = false;
      }, 100);
      const res = await productionSelect(val);
      let { data } = res;
      // console.log(JSON.stringify(data.data));
      if (data.code == 200) {
        data.data = { ...data.data, ...data.data.materialFields.skuEntity };
        data.data.materialFields.skuId = data.data.skuId;
        data.data.materialFields.skuEntity = {
          ...data.data.materialFields.skuEntity,
        };
        data.data.materialFields.skuEntity.skuId = data.data.materialFields
          .skuEntity.skuId
          ? data.data.materialFields.skuEntity.skuId
          : data.data.skuId;
        let params = encodeURIComponent(JSON.stringify(data.data));
        this.$router.push("/allocationDetail?type=scan&data=" + params);
      } else {
        Dialog.alert({
          title: "扫码提示",
          message: res.data.message,
          confirmButtonColor: "#548AF1",
          showCancelButton: false,
        });
      }
    },
    selectMaterial(item) {
      // this.selectMaterialData = {
      //   code: item.code,
      //   name: item.name,
      //   isBatchMag: item.isBatchMag,
      // };
    },
    async selectSubmit() {
      const addlist = this.list.filter((i) => i.checked);
      if (addlist.length == 0) {
        Toast("请至少选择一条数据");
        return;
      }
      const selectData = JSON.parse(localStorage.getItem("selectData"));
      selectData.stockMaterialDetaiList = addlist[0];
      localStorage.setItem("selectData", JSON.stringify(selectData));
      if(this.$route.query.type == 'allocationDetailForm'){
        this.$router.replace({
          path: "/allocationDetail/form",
          query: {
            id: this.$route.query.id,
            orderNumber: this.$route.query.orderNumber,
            warehouseCode: this.$route.query.warehouseCode,
            materialInfo: this.$route.query.materialInfo,
          },
        });
      }else{
        this.$router.replace({
          path: "/batch",
          query: {
            id: this.$route.query.id,
            orderNumber: this.$route.query.orderNumber,
            warehouseCode: this.$route.query.warehouseCode,
            materialInfo: this.$route.query.materialInfo,
          },
        });
      }
      
    },
  },
};
</script>
  <style lang="scss" scoped>
@import "../../assets/css/common.scss";
.scan-img {
  position: fixed;
  bottom: 1vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.work-order-list {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .search-box {
    // height: 46px;
    position: relative;
    .inner {
      font-size: 16px;
      color: #fff;
      padding: 8px 12px;
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .van-search {
      flex: 1;
      padding: 0px 15px 0 3px;
      // height: 32px;
      border-radius: 4px;
      border: 1px #dedede solid;
    }
    .van-search__content {
      background-color: #ffffff;
      height: 32px;
      .van-cell {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
    .btn-wrap {
      width: 62px;
      height: 32px;
      background: #548af1;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 7px;
      font-size: 14px;
      color: #fff;
    }
    .scan-box {
      display: flex;
      align-items: center;
      img {
        width: 20px;
      }
    }
  }
  .van-pull-refresh {
    height: 100%;
    overflow: scroll;
    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }
    .van-list {
      height: 100%;
      // overflow: scroll;
    }
    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }
}
.sure-dialog {
  border-radius: 4px;
}
.model-content {
  padding: 25px 10px 20px 26px;
  .name {
    font-size: 14px;
    color: #666666;
  }
  .value {
    font-size: 16px;
    color: #548af1;
    margin-top: 10px;
  }
}
.footer {
  align-items: center;
  display: flex;
  .footer-l {
    width: 120px;
  }
}
</style>
  <style lang="scss">
.van-overlay {
  // z-index: 2000 !important;
}
</style>
  